package com.tencent.sr.iris.activity.repository.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.reactor.IOReactorException;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * es配置
 *
 * @author nixiaolin
 * @date 2023/2/19 15:51
 */
@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "spring.elasticsearch")
public class EsClientConfig {

    String password;
    String username;
    String host;
    Integer port;

    @Bean(destroyMethod = "close", name = "RestHighLevelClient")
    public RestHighLevelClient initRestClient() throws IOReactorException {

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
                .setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2)
                .setConnectTimeout(1000)
                .setTcpNoDelay(true)
                .setSoReuseAddress(true)
                .setRcvBufSize(8192)
                .setSndBufSize(8192)
                .build();
        final PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(
                new DefaultConnectingIOReactor(ioReactorConfig));
        connManager.setMaxTotal(100);
        connManager.setDefaultMaxPerRoute(100);
        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(host, port));
        restClientBuilder
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                        .setDefaultIOReactorConfig(IOReactorConfig.custom()
                                .build()
                        )
                        .setDefaultCredentialsProvider(credentialsProvider)
                        .setConnectionManager(connManager)
                );
        return new RestHighLevelClient(restClientBuilder);
    }

}
